import {
  reqGoodDetailData
} from '../../../api/goods'
import {
  reqGetCartList,
  reqAddToCart
} from '../../../../../api/cart'
import {
  userBehavior
} from './behavior'
Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  data: {
    loading: true,
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    allCount: 0, // 购物车商品总数量
    buyType: 0 // 购买方式 0 加入购物车 1 立即购买
  },
  onLoad(options) {
    const {
      goodsId
    } = options
    this.goodsId = goodsId
    this.initData(goodsId)
    this.getCarCount()
  },
  async initData(id) {
    const res = await reqGoodDetailData(id)
    this.setData({
      goodsInfo: res.data,
      loading: false
    })
  },

  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyType: 0,
      blessing: ''
    })
  },

  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      buyType: 1,
      blessing: ''
    })
  },

  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({
      show: false
    })
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    this.setData({
      count: Number(event.detail)
    })
  },
  // 确定
  async handlerSubmit() {
    const goodsId = this.goodsId
    const {
      token,
      blessing,
      buyType,
      count
    } = this.data

    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }

    if (!blessing) {
      wx.flowerTipToast({
        title: '请填写祝福语',
        icon: 'error'
      })
      return
    }
    // 加入购物车
    if (buyType === 0) {
      const {
        code,
        message
      } = await reqAddToCart({
        goodsId,
        count
      })
      if (code === 200) {
        wx.flowerTipToast({
          title: message,
          icon: 'success'
        })
        this.getCarCount()
        this.setData({
          show: false
        })
      }
    } else {
      // 立即购买
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`,
      })
    }
  },
  // 获取购物车数量
  async getCarCount() {
    const {
      code,
      data
    } = await reqGetCartList()
    if (code === 200) {
      this.setData({
        allCount: data.reduce((prev, next) => (prev + next.count), 0)
      })
    }
  },
  // 详情图片预览
  handlePreview(event) {
    const {
      images,
      src
    } = event.currentTarget.dataset;
    wx.previewImage({
      urls: images,
      current: src
    });
  }
})